
from operator import and_
from app.libs.exception import Forbidden, NotFound
from app.libs.forms import LoginForm, RegisterForm
from app.models.user import User
from app.service.token import TokenService
from .base import BaseService


class UserService(BaseService):
    """
        功能：
            1. 注册
            2. 登录
            3. 获取用户信息
            4. 获取用户的所有视频 # detail & pure
            5. 获取用户的章节 # pure
            6. 获取课程信息 # pure exclude 视频的详细信息
    """
    @classmethod
    def register(cls, form: RegisterForm) -> User:
        new_user = User().set_attr(form)  # 创建注册对象
        user = User.query.filter(
            User.account == new_user.account).first()  # 判单用户存在与否
        if user:
            raise Forbidden(f'用户(account: {user.account})已存在')
        else:
            User.session.add(new_user)
            User.session.commit()

        return new_user, TokenService.create_token(new_user)

    @classmethod
    def login(cls, form: LoginForm) -> User:
        temp_user = User().set_attr(form)  # 创建登录对象 @NOTE 没有id没有值
        user = User.query.filter(
            and_(User.account == temp_user.account, User.password == temp_user.password)).first()
        if not user:
            raise NotFound('账号或密码错误。')
        return user, TokenService.create_token(user=user)
